﻿
using Sys;

using System.Silverlight;
using System.Silverlight.Presentation;
using System.Silverlight.Presentation.Animation;

namespace SBT
{
    public class ToggleButton : Button
    {
        public ToggleButton()
        {
        }

        private bool m_isPushed = false;

        public bool IsPushed
        {
            get { return m_isPushed; }
            set
            {
                if(m_isPushed != value)
                {
                    bool old = m_isPushed;
                    m_isPushed = value;
                    OnIsPushedChanged(old, value);
                }
            }
        }

        public void add_pushed(EventHandler handler)
        {
            this.Events.AddHandler("pushed", handler);
        }
        public void add_unpushed(EventHandler handler)
        {
            this.Events.AddHandler("unpushed", handler);
        }
        public void remove_pushed(EventHandler handler)
        {
            this.Events.RemoveHandler("pushed", handler);
        }
        public void remove_unpushed(EventHandler handler)
        {
            this.Events.RemoveHandler("unpushed", handler);
        }
        protected virtual void OnIsPushedChanged(bool oldValue, bool newValue)
        {
            RaisePropertyChanged("isPushed");
            if (newValue)
            {
                RaiseEvent("pushed");
                if (this.MouseDownAnim != null)
                {
                    this.MouseDownAnim.Begin();
                }
            }
            else
            {
                RaiseEvent("unpushed");
                if (this.MouseUpAnim != null)
                {
                    this.MouseUpAnim.Begin();
                }
            }
        }

        protected override void OnMouseUp(object sender, MouseEventArgs args)
        {
            Debug.Trace("Up");
            this.Element.ReleaseMouseCapture();
            if (this.IsMouseInner)
            {
                RaiseEvent("click");
                if (IsPushed)
                {
                    
                    IsPushed = false;
                }
                else
                {
                    IsPushed = true;
                }
            }
            else
            {
                if ((bool)(object)MouseLeaveAnim)
                {
                    MouseLeaveAnim.Begin();
                }
            }
            IsMouseDown = false;
        }
    }
}